package GormSrv

import (
	"fmt"
	"gin-service/config"
	"gin-service/lib/GormSrv/model"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var GormDB *gorm.DB

func GDB() *gorm.DB {
	if GormDB == nil {
		panic("GORM DB instance is null")
	}

	if config.GlobalRunningEnv == "development" {
		return GormDB.Debug()
	} else {
		return GormDB
	}
}

func GormInit(config interface{}) *gorm.DB {
	mysqlConfig := config.(map[string]interface{})
	username := mysqlConfig["username"]
	password := mysqlConfig["password"]
	database := mysqlConfig["database"]
	charset := mysqlConfig["charset"]
	parseTime := mysqlConfig["parseTime"]
	loc := mysqlConfig["loc"]

	mysqlConfigString := fmt.Sprintf("%s:%s@/%s?charset=%s&parseTime=%s&loc=%s", username, password, database, charset, parseTime, loc)
	fmt.Println("mysqlConfigString:", mysqlConfigString)

	db, err := gorm.Open("mysql", mysqlConfigString)
	if err != nil {
		panic("failed to connect mysql database")
	}

	// 全局禁用表名复数
	db.SingularTable(true)

	//创建/更新表
	db.AutoMigrate(&model.Demo{})
	db.AutoMigrate(&model.DemoSub{})
	db.AutoMigrate(&model.Order{})
	db.AutoMigrate(&model.OrderGoods{})
	db.AutoMigrate(&model.User{})
	db.AutoMigrate(&model.UserClient{})

	GormDB = db
	return db
}
